<template>
    <ZwSearchForm row-num="4" :option="searchOption" @search="search" @reset="reset" @expand="getTableH" />
    <ZwTable
        ref="sopTableRef"
        class="table-box"
        tab-h="initial"
        :option="tableOption"
        :fetch-params="state.searchParams"
        :fetch-api="fetchApi()">
        <template #headerOperate>
            <el-button class="high_btn" @click="highSet">高级设置</el-button>
            <el-dropdown @command="handleCommand">
                <el-button v-auth="'CREATE_SOP'" type="primary">
                    创建客户SOP
                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item v-for="item in sopScene" :key="item.id" :command="item.id">
                            {{ item.name }}
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </template>
    </ZwTable>
    <SopDrawer ref="sopDra"></SopDrawer>
    <Dialog :app-dialog="appDialog">
        <div class="title">确定要删除该SOP规则吗?</div>
    </Dialog>
    <ZWadvancedSetup ref="advanced" :type="4"></ZWadvancedSetup>
    <Taskdetail ref="taskdetail" :type="1" :tooltip="tooltip"></Taskdetail>
</template>

<script lang="tsx" setup>
import { reactive, ref, computed, nextTick, onActivated } from 'vue';
import { getSopList, delSop, amendSopStatus, scene } from '@/api/smartMarketing/sop';
import { getCreateList } from '@/api/common';
import SopDrawer from './SopDrawer.vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWadvancedSetup from '@/components/ZWadvancedSetup.vue';
import Taskdetail from '../../components/Taskdetail.vue';
import { deepCopy } from '@/utils/helper';
import { dividerProps, ElButton, ElMessage, ElPopover } from 'element-plus';
import { ArrowDown } from '@element-plus/icons-vue';
import router from '@/router';
import Dialog from '@/components/Dialog.vue';

const sopDra = ref();
const sopTableRef = ref(null);
const advanced: any = ref(null);
const taskdetail: any = ref(null);
const sopScene = ref([{ id: '', name: '' }]);
const sopRuleId = ref();
const goSop = new Map();
const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);
const sopBtnList = reactive([
    { id: 1, val: '开启', authCode: 'OPEN_SOP' },
    { id: 2, val: '关闭', authCode: 'CLOSE_SOP' },
    { id: 3, val: '查看', authCode: 'LOOK_SOP' },
    { id: 4, val: '编辑', authCode: 'EDIT_SOP' },
    { id: 5, val: '执行详情', authCode: 'FINISH_SOP' },
    { id: 6, val: '克隆规则', authCode: 'COPY_SOP' },
    { id: 7, val: '删除', authCode: 'DEL_SOP' }
]);
const tooltip = {
    mass_num: {
        title: '执行群发数',
        text: '触达方式为：员工消息群发时，当员工在收到群发助手的消息提醒时，点击“发送”的群发数。'
    },
    fail_num: {
        title: '执行失败数',
        text: '触达方式为：员工消息群发时，当员工点击“发送”后，发送结果中有客户“接收次数已达上限”的群发数。',
        text2: '触发方式为：短信时，发送短信失败数。'
    },
    letter_num: { title: '员工私信完成数', text: '执行群发失败后，员工私信完成的任务数。' }
};

/* eslint-disable */
const searchOption = computed(() => {
    return [
        {
            label: '规则名称',
            name: 'keywords',
            value: '',
            type: 'input',
            placeholder: '请输入规则名称'
        },
        {
            label: '创建人',
            name: 'created_uids',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '执行人',
            name: 'executor_uids',
            value: [],
            type: 'select',
            placeholder: '请选择执行人',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },

        {
            label: 'SOP状态',
            name: 'status',
            value: '',
            type: 'select',
            placeholder: '请选择SOP状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        {
                            name: '全部',
                            id: -1
                        },
                        {
                            name: '已开启',
                            id: 1
                        },
                        {
                            name: '已关闭',
                            id: 2
                        }
                    ]);
                });
            },
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        ,
        {
            label: 'SOP场景',
            name: 'sop_scene',
            value: '',
            type: 'select',
            placeholder: '请选择SOP场景',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    scene().then((data: any) => {
                        data.unshift({ name: '全部', id: -1 });
                        resolve(data);
                    });
                });
            },
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'created_at',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
            // 设置结束日期时间为 23:59:59，设完日期不能点击 elment-plus bug？
            // defaultTime: ['00:00:00', '23:59:59']
        }
    ];
});
/* eslint-enable */

const defaultParams = reactive({
    keywords: '',
    created_uids: '',
    executor_uids: [],
    status: -1,
    sop_scene: -1,
    created_at: []
});

const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const tableOption = [
    {
        prop: 'name',
        label: 'SOP规则名称',
        minWidth: 240
    },
    {
        prop: 'trigger_range',
        label: 'SOP场景',
        width: 200,
        render({ row }: any) {
            return (
                <div>
                    {sopScene.value.map((i: any, n) => {
                        return (
                            <span v-auth={i.authCode} v-show={i.id == row.sop_scene}>
                                {i.name}
                            </span>
                        );
                    })}
                </div>
            );
        }
    },
    {
        prop: 'trigger_range',
        label: '触发范围',
        width: 300
    },
    {
        prop: 'status',
        label: 'SOP状态',
        width: 120,
        render({ row }: any) {
            return (
                <div>
                    <p>{row.status == 1 ? <span style="color:#60B900">已开启</span> : '已关闭'}</p>
                </div>
            );
        }
    },
    {
        prop: 'executor_list',
        label: '执行人',
        showOverflowTooltip: true,
        minWidth: 300,
        render({ row }: any) {
            const slotReference = () => (
                <div>
                    {row.executor_list.map((item: any, index: any) => {
                        return (
                            <span>
                                {item.name}
                                <span v-show={row.executor_list.length - 1 !== index}>、</span>
                            </span>
                        );
                    })}
                </div>
            );
            const slotDefault = () => (
                <div>
                    {row.executor_list.map((item: any, index: any) => {
                        return (
                            <span style={executor}>
                                {item.name}
                                <span v-show={row.executor_list.length - 1 !== index}>、</span>
                            </span>
                        );
                    })}
                </div>
            );
            return (
                <div>
                    <div v-show={row.executor_list.length <= 8}>
                        {row.executor_list.map((item: any, index: any) => {
                            return (
                                <span>
                                    {item.name}
                                    <span v-show={row.executor_list.length - 1 !== index}>、</span>
                                </span>
                            );
                        })}
                    </div>
                    <div v-show={row.executor_list.length > 8}>
                        <ElPopover
                            popper-class="popGroup"
                            trigger="hover"
                            vSlots={{ reference: slotReference, default: slotDefault }}
                            width={300}
                            popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
                    </div>
                </div>
            );
        }
    },
    {
        prop: 'created_at',
        label: '创建时间',
        slotName: 'header',
        width: 240
    },
    {
        prop: 'rule_list',
        label: '推送内容规则标题',
        width: 380,
        showOverflowTooltip: true,
        render({ row }: any) {
            return (
                <p class="rule">
                    {row.rule_list.map((item: any, index: any) => {
                        return (
                            <span class="rule_item">
                                {item.title}
                                <span v-show={row.rule_list.length - 1 !== index}>、</span>
                            </span>
                        );
                    })}
                </p>
            );
        }
    },

    {
        prop: 'operate',
        label: '操作',
        width: 300,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }: any) {
            return sopBtnList.map((item: any, index: number) => {
                return (
                    <ElButton
                        size="small"
                        v-show={item.id != row.status}
                        disabled={row.status != 2 ? (item.id == 4 || item.id == 7 ? true : false) : false}
                        onClick={() => sopBtn(row, item.id)}>
                        {item.val}
                    </ElButton>
                );
            });
        }
    }
];
// 获取表格高度
const getTableH = () => {
    nextTick(() => {
        sopTableRef.value.getTableH();
    });
};
const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return getSopList;
};
const search = (data: any) => {
    currentParams.value = data;
    state.searchParams = deepCopy(data);
};
const reset = (v: any) => {
    state.searchParams = deepCopy(defaultParams);
    currentParams.value = null;
};
const getScene = () => {
    scene().then((res: any) => {
        sopScene.value = res;
        sopScene.value.map((item: any) => {
            goSop.set(item.id, `/smartMarketing/marketAutomation/customerSop/createSop?scene=${item.id}`);
        });
    });
};
getScene();

// 高级设置
const highSet = () => {
    advanced.value.isShow = true;
};
const handleCommand = (command: any) => {
    router.push(goSop.get(parseInt(command)));
};
// 去创建 SOP
const creatSop = () => {
    // router.push('/smartMarketing/marketAutomation/customerSop/createSop')
};
// 操作按钮
const sopBtn = (btn: any, num: number) => {
    const status = (val: number) => {
        const params = {
            market_sop_id: btn.id,
            status: val
        };
        amendSopStatus(params)
            .then((res: any) => {
                sopTableRef.value.reload();
                ElMessage.success('SOP状态修改成功');
            })
            .catch((e: any) => {
                ElMessage.error('SOP状态修改失败');
            });
    };
    let text: string;
    let name: string;
    let name2: string;
    let isCopy: string | number;
    let t: string;
    switch (num) {
        case 1:
            status(1);
            break;
        case 2:
            status(2);
            break;
        case 3:
            router.push('/smartMarketing/marketAutomation/customerSop/createSop?type=look&&id=' + btn.id);
            break;
        case 4:
            router.push('/smartMarketing/marketAutomation/customerSop/createSop?type=edit&&id=' + btn.id);
            break;
        case 5:
            taskdetail.value.drawer = true;
            taskdetail.value.drawerData = btn;
            taskdetail.value.defaultParams.sop_id = btn.id;
            // sopDra.value.state.searchParams.market_sop_id = btn.id
            // sopDra.value.open(btn.name, btn.id)
            break;
        case 6:
            text = '';
            name = btn.name.substring(btn.name.length - 3);
            isCopy = btn.name.search('-副本');
            if (isCopy != -1) {
                if (name.length <= 3) {
                    name2 = name.substring(name.length - 1);
                    if (name2 >= 1) {
                        t = btn.name.slice(0, btn.name.length - 4);
                        text = t + '-副本' + (+name2 + 1);
                    } else {
                        text = btn.name + 2;
                    }
                }
            } else {
                text = btn.name + '-副本';
            }
            router.push({
                path: '/smartMarketing/marketAutomation/customerSop/createSop',
                query: { id: +btn.id, type: 'copy', copy: text }
            });
            break;
        case 7:
            sopRuleId.value = btn.id;
            appDialog.visible = true;
            break;
    }
};
const cancelHandel = () => {
    appDialog.visible = false;
};
const submitHandel = () => {
    delSop({ market_sop_id: sopRuleId.value }).then((res: any) => {
        ElMessage.success('删除成功');
        cancelHandel();
        sopTableRef.value.reload();
    });
};
// 弹框配置项
const appDialog = reactive({
    visible: false,
    title: '提示',
    width: '30%',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
});
const executor = {
    color: '#000000',
    ['font-size']: '12px'
};
onActivated((val: any) => {
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
});
</script>

<style scoped lang="scss">
:deep(.sopBtn) {
    padding: 4px 16px 2px;
    margin: 3px;
    min-height: 0;
}

:deep(.executor) {
    height: 40px;
    overflow: hidden;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    text-overflow: ellipsis;
}

:deep .rule {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;

    &_item {
        width: 350px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
}

.title {
    text-align: center;
    padding: 50px 0;
}

:deep(.el-dropdown-menu__item) {
    justify-content: center;
}

.high_btn {
    margin-right: 14px;
}

.zw-table {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: hidden;

    :deep(.el-table) {
        flex: 1;

        .el-table__empty-block {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    }
}
</style>
